package com.car.framework;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;

import com.car.comm.Logger;
import com.car.comm.Outter;
import com.car.comm.Variable;
import com.car.postoffice.CAddress;
import com.car.postoffice.CMailHeader;
import com.car.postoffice.CMailReply;
import com.car.postoffice.IMailBox;
import com.car.postoffice.IMailHandler;
import com.car.postoffice.PostOffice;
import com.car.postoffice.SendException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.os.Bundle;

public class FrameActivity extends Activity implements IMailHandler{
	public static ArrayList<Activity> activityList = new ArrayList<Activity>();  
	 
	private HashMap<Integer, List<ImageListener>> imageIdMap 
						= new HashMap<Integer, List<ImageListener>>();
	protected boolean atHome;
	protected CAddress addr;
	protected IMailBox mailBox;
	protected PostOffice office;
	
	public FrameActivity(){
	}
	
	private void Init(String scheme){
		addr = new CAddress(scheme, this.getClass().getName());
		mailBox = FrameworkFactory.CreateMailBox(addr);
		office = FrameworkFactory.GetOffice();
		office.RegisterHandler(this.addr, this);
	}
	
	public void SetUpBackGround(String scheme){
		this.atHome = true;
		Init(scheme);
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		atHome = false;
		Init("Activity");
		activityList.add(this);
	}
    
    @Override
    protected void onResume(){
    	super.onResume();
    	atHome = true;
    	while(!mailBox.isEmpty()){
    		CMailReply reply = mailBox.GetMail();
    		HandleReply(reply);
    	}
    }
    
    @Override
    protected void onPause(){
    	super.onPause();
    	atHome = false;
    }
    
    @Override
    protected void onDestroy(){
    	super.onDestroy();
    	office.UnRegisterHandler(this.addr);
    	activityList.remove(this);
    	
    	// 移除图像控件中所有引用的图片
    	ImageManager imgManager = GetImageManager();
    	for(Entry<Integer, List<ImageListener>> entry : imageIdMap.entrySet()){
    		imgManager.ReleaseImage(addr, entry.getKey());
    	}
    }
    
	@Override
	public boolean isAtHome() {
		return atHome;
	}

	@Override
	public CAddress Addr() {
		return addr;
	}

	@Override
	public void PutMail(CMailReply reply) {
		mailBox.PutMail(reply);
	}
	
	
	@Override
	public void HandleReply(CMailReply reply) {
		CMailHeader header = reply.getHeader();
		if(header.getMailType().equals(Variable.bitmapType)){
			ImageManager imageManger = GetImageManager();
			Bitmap bmp = imageManger.Instance(header.getMailId());
			List<ImageListener> lst = this.imageIdMap.get(header.getMailId());
			for(ImageListener listener : lst){
				if(listener != null){
					listener.ImageChange(header.getMailId(), bmp);
				}
			}
		}
	}
	
	protected ImageManager GetImageManager(){
		return FrameworkFactory.GetImageManager();
	}
	
	/**
	 * @param uri[in] 图片地址
	 * @param list[in] 图片变化的监听者
	 * @return 0 表示失败，其他表示图像的ID
	 */
	protected int GetImage(String uri, ImageListener listener){
		if(listener == null){
			return 0;
		}
		Outter<Bitmap> oBitmap = new Outter<Bitmap>();
		int id = 0;
		try {
			id = GetImageManager().GetImage(addr, uri, oBitmap);
			if(oBitmap.getInstance() != null){
				listener.ImageChange(id, oBitmap.getInstance());
			}
			List<ImageListener> listenersArray = imageIdMap.get(id);
			if(listenersArray == null){
				listenersArray = new ArrayList<ImageListener>();
				imageIdMap.put(id, listenersArray);
			}
			if(!listenersArray.contains(listener)){
				listenersArray.add(listener);
			}
		} catch (SendException e) {
			Logger.LogErr(e.getMessage());
		}
		return id;
	}
	
	/*
	 * 移除对一个图像上监听的绑定
	 */
	protected void RemoveImage(int id, ImageListener listener){
		List<ImageListener> listenersArray = imageIdMap.get(id);
		if(listenersArray == null){
			return ;
		}
		listenersArray.remove(listener);
		if(listenersArray.size() == 0){
			// 说明已经没有监听器了,  去除引用
			GetImageManager().ReleaseImage(addr, id);
			imageIdMap.remove(id);
		}
	}
	
	public void exitApp() {  
		AlertDialog.Builder builder = new AlertDialog.Builder(this);  
		builder.setTitle("提示");  
		builder.setMessage("您确定要退出程序吗?");  
		builder.setPositiveButton("确定", new OnClickListener() {  

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (activityList.size() > 0) {
					for (Activity activity : activityList) {
						activity.finish();
					}
					android.os.Process.killProcess(android.os.Process.myPid());
				}
			}
		});
		builder.setNegativeButton("取消", null);
		builder.show();
	} 
	
	@Override
	public void onBackPressed() {
		if(activityList.size() == 1){
			// 说明这是最后一个视图， 提示用户是否退出
			exitApp();
		}
		else{
			super.onBackPressed();
		}
	}
    

}
